<template>
  <el-container direction="vertical">

    <navMenu width="100%"></navMenu>
    <el-container direction="horizontal">
      <el-aside width="280px" height="100%">
        <sideBar class="menu" page-index="2-3" open-index="2"></sideBar>
      </el-aside>
      <el-main>
        <el-card>
          <div>
            <h2>老人年龄统计图</h2>
            <div id="chart_example1"></div>
          </div>
        </el-card>
      </el-main>
    </el-container>
  </el-container>

</template>


<script>
import sideBar from "@/components/sideBar";
import navMenu from "@/components/navMenu";
import * as echarts from 'echarts'

export default {
  components: {sideBar, navMenu},
  data() {
    return {
      old_age:[1,1,1,1,1,1,1,1,1]
    }
  },
  mounted() {
    this.drawLine(); //按照默认值绘制图表
  },
  methods: {
    drawLine() {
      let myChart = echarts.init(document.getElementById("chart_example1"));
      //2、构造图表数据
      let options = {
        title: {
          text: "年龄情况分析",
          left: "center",
          tooltip: {},
        },
        xAxis: {
          data: [
            "50岁以下",
            "50-55",
            "55-60",
            "60-65",
            "65-70",
            "70-75",
            "75-80",
            "80-85",
            "85岁以上",
          ],
        },
        yAxis: {},
        series: [
          {
            name: "年龄",
            type: "bar",
            data:this.old_age,
          },
        ],
      };
      // 3、绘制图表
      myChart.setOption(options);
      window.addEventListener( 'resize', function () {
        myChart.resize()
      } );
    },
  },
  watch: {
    old_age: {
      //对于深层对象的属性，watch不可达，因此对数组监控需要将数组先清空，再添加数据
      handler: function () {
        this.drawLine();
      },
      deep: true,
    },
  },
  created() {
    this.$axios.get("http://127.0.0.1:5000/select_age").then((res) => {
      // this.emp_age.fill(0); //数组清零
      this.old_age.length=0;
      for(let i=0;i<9;i++){
        this.old_age.push(0);
      }
      for (let i = 0; i < res.data.length; i++) {
        const age = parseInt( res.data[i].age );
        if(age<50){
          this.old_age[0]+=1;
        }else if(age>=50&&age<55){
          this.old_age[1]+=1;
        }else if(age>=55&&age<60){
          this.old_age[2]+=1;
        }else if(age>=60&&age<65){
          this.old_age[3]+=1;
        }else if(age>=65&&age<70){
          this.old_age[4]+=1;
        }else if(age>=70&&age<75){
          this.old_age[5]+=1;
        }else if(age>=75&&age<80){
          this.old_age[6]+=1;
        }else if(age>=80&&age<85){
          this.old_age[7]+=1;
        }else if(age>=85){
          this.old_age[8]+=1;
        }
      }

    });
  }
}
</script>
<style scoped>
h2 {
  text-align: center;
  padding: 30px;
  font-size: 18px;
}

#chart_example1 {
  width: 65%;
  height: 300px;
  border: 1px solid #000000;
  margin: 0 auto;
}
</style>
